package com.founder.gateway.oauth.cover;

import com.founder.gateway.oauth.service.OAuthService;
import com.founder.gateway.system.consts.Consts;
import com.founder.oauth.expand.OAuthTokenEnhancer;
import com.founder.oauth.utils.AuthorityUtils;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Component
public class TokenExpandEnhancer implements OAuthTokenEnhancer {
    @Resource
    private OAuthService oAuthService;

    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
        DefaultOAuth2AccessToken token = new DefaultOAuth2AccessToken(accessToken);
        Map<String, Object> map = accessToken.getAdditionalInformation();
        map = map == null ? new HashMap<>() : new HashMap<>(map);
        if (AuthorityUtils.anyMatch(authentication.getAuthorities(), AuthorityUtils.ROLE_CLIENT)) {
            map.put(Consts.TOKEN_AID, oAuthService.getClientByAppKey(authentication.getName()).getId());
            token.setAdditionalInformation(map);
        }
        return token;
    }
}
